package com.geek.config.microprofile;


import com.geek.config.convert.StringConvert;
import com.geek.config.microprofile.source.value.DefaultValue;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigValue;
import org.eclipse.microprofile.config.spi.ConfigSource;
import org.eclipse.microprofile.config.spi.Converter;

import java.security.Key;
import java.util.*;

import static java.util.stream.StreamSupport.stream;

/**
 * @Author: ysq
 * @Date: 2021/7/14
 * @Description:
 */
public class DefaultConfig implements Config {

  private final ConfigSources configSources;
  private final StringConvert convert;

  public DefaultConfig(final ConfigSources configSources, final StringConvert convert) {
    this.configSources = configSources;
    this.convert = convert;
  }
  @Override
  public <T> T getValue(String s, Class<T> aClass) {
    ConfigValue configValue = getConfigValue(s);
    return (T) configValue.getValue();
  }

  @Override
  public ConfigValue getConfigValue(String key) {
    for (final ConfigSource next : configSources) {
      String value = next.getValue(key);
      if (value != null) {
        return new DefaultValue(key, value, value, next.getName(), next.getOrdinal());
      }
    }
    return null;
  }

  @Override
  public <T> Optional<T> getOptionalValue(String s, Class<T> aClass) {
    T value = getValue(s, aClass);
    return Optional.ofNullable(value);
  }

  @Override
  public Iterable<String> getPropertyNames() {
    return stream(configSources.spliterator(), false)
            .map(ConfigSource::getPropertyNames)
            .collect(LinkedHashSet::new, Set::addAll, Set::addAll);
  }

  @Override
  public Iterable<ConfigSource> getConfigSources() {
    return configSources;
  }

  @Override
  public <T> Optional<Converter<T>> getConverter(Class<T> aClass) {
    return Optional.empty();
  }

  @Override
  public <T> T unwrap(Class<T> aClass) {
    return null;
  }
}
